<template>
  <div id="wrapper">
    <el-row style="height: 10%">
      <el-col :span="12"><h1>小海海的聊天室</h1></el-col>
      <el-col :span="12" style="text-align: right;margin: auto 20px auto 0;">当前在线人数： {{ onlineCount }}</el-col>
    </el-row>
    <el-row style="height: 80%">
      <el-col :span="24">
        <chat-item v-for="(message, index) in chatList" :customerMessage="message" :key="index"/>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="18">
        <el-input v-model="customerMessage" @keydown.enter="sendMessage" placeholder="消息内容..."></el-input>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="sendMessage" plain>发送</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import ChatItem from './ChatItem'

export default {
  name: 'ChatRoom',
  data() {
    return {
      socketInfo: {
        path: 'ws://127.0.0.1:8080/default/websocket',
        socket: null
      },
      onlineCount: 0,
      chatList: [],
      customerMessage: ''
    }
  },

  mounted() {
    // 初始化 WebSocket
    this.init()
  },

  destroyed() {
    this.socketInfo.socket.close();
  },

  methods: {
    /**
     * 初始化WebSocket
     */
    init() {
      if (typeof (WebSocket) === 'undefined') {
        alert('您的浏览器不支持WebSocket')
      } else {
        const socket = new WebSocket(this.socketInfo.path)

        // 发送消息的事件
        socket.onmessage = this.getMessage
        // socket被打卡的事件
        socket.onopen = this.socketOpen

        this.socketInfo.socket = socket
      }
    },
    socketOpen() {
      this.chatList.push('您已经进入聊天室，可以开始聊天了！')
    },
    /**
     * 发送消息给服务端
     */
    sendMessage() {
      if (this.customerMessage === '') alert('发送消息不能为空')
      this.socketInfo.socket.send(this.customerMessage)
      this.customerMessage = ''
    },
    /**
     * 收到服务器发过来的消息
     * @param message 消息对象
     */
    getMessage(message) {
      // 将接收到的消息转换为json格式
      const messageJson = JSON.parse(message.data)
      if (messageJson.type === 0) {
        this.onlineCount = messageJson.message
      } else if (messageJson.type === 1) {
        this.chatList.push(messageJson.message)
      }
    }
  },

  components: {
    ChatItem
  }
}
</script>

<style scoped>

</style>
